package com.springcloud.market.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.springcloud.market.order.feign.StockFeignService;
import com.springcloud.market.order.pojo.Order;
import com.springcloud.market.order.service.OrderService;
import com.springcloud.mastrk.conpon1.service.ConponService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springcloud.market.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

@RestController
@RefreshScope
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private StockFeignService stockFeignService;
    @DubboReference
    private ConponService conponService;
    @DubboReference
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @RequestMapping("/getUserInfo")
    public String getUserInfo(){
    return userService.getUserInfo();
    }

    @RequestMapping("/readOrder")
    public String readOrder(){
        System.out.println("网关测试：order服务");
        return "网关测试：order服务";
    }

    @GetMapping("/createOrder")
    @SentinelResource(value = "orderApi", blockHandler = "handleFlowBlock")
    public String createOrder() {
        return "订单创建成功! (Time: " + System.currentTimeMillis() + ")";
    }
    public String handleFlowBlock(BlockException ex) {
        return "请求过于频繁，请稍后再试! (触发限流)";
    }

    @GetMapping("/getUser")
    @SentinelResource(value = "userApi", blockHandler = "handleDegradeBlock")
    public String getUser(){
        // 模拟业务逻辑：随机产生异常，模拟服务不稳定
        if (Math.random() > 1) {
            throw new RuntimeException("查询用户信息失败，数据库异常");
        }
        return userService.getUserInfo();
    }
    public String handleDegradeBlock(BlockException ex) {
        return "服务暂时不可用，请稍后重试! (触发熔断)";
    }

    @RequestMapping("/getUserInfo1")
    public String getUserInfo1(){
        return conponService.getUserInfo1();
    }
    @RequestMapping("/add")
    public String add(){
        return stockFeignService.reduce();
    }
    @RequestMapping("/seata/add")
    public Order seataOrder (@RequestBody Order order){
        return orderService.create(order);
    }

    @GetMapping("/createOrder2")
    public Order createOrder2(){
        return orderService.createOrder();
    }

//    @Value("${user.name}")
//    private String name;
//    @Value("${user.age}")
//    private Integer age;
//
//    @RequestMapping("/info")
//    public String info(){
//        return "姓名："+name+"，年龄："+age;

//    }

}
